package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
public class SetmealController {
    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    // /setmeal/add
    @RequestMapping("/setmeal/add")
    public Result add(Integer []checkgroupIds,@RequestBody Setmeal setmeal){
        return setmealService.add(checkgroupIds,setmeal);
    }

    //  /setmeal/findPage
    @RequestMapping("/setmeal/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }

    // 图片上传的 资源路径
    // /setmeal/upload
    @RequestMapping("/setmeal/upload")
    // @RequestParam("imgFile") 的值一定要和文件 上传组件 中的name的值一样
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){

        try {
            //获取 在上传方本地的的文件名
            String originalFilename = imgFile.getOriginalFilename();
            //获取最后一个 . 的 索引值
            int index = originalFilename.lastIndexOf(".");
            //截取 .后缀名
            String substring = originalFilename.substring(index - 1);
            String fileName = UUID.randomUUID().toString()+substring;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);

            //如果最后上传没报错，则将文件名 存放进set集合
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);


            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

}
